package com.hdu.other.nestedRecursion;


import java.util.TreeMap;

public class lc726 {
    class Solution
    {
        int where;

        public String countOfAtoms(String s)
        {
           TreeMap<String, Integer> ans = f(s.toCharArray(), 0);
           StringBuilder sb = new StringBuilder();
            for (String key : ans.keySet()) {
                sb.append(key);
                if (ans.get(key) > 1) {
                    sb.append(ans.get(key));
                }
            }
            return sb.toString();
        }

        TreeMap<String, Integer> f(char[] s, int i)
        {
            TreeMap<String, Integer> ans = new TreeMap<>();
            TreeMap<String, Integer> prev = null;
            StringBuilder name = new StringBuilder();
            int cur = 0;
            while (i < s.length && s[i] != ')')
            {
                if (Character.isDigit(s[i]))
                {
                    cur = cur * 10 + s[i++] - '0';
                }
                else if ('a' <= s[i] && s[i] <= 'z')
                {
                    name.append(s[i++]);
                }
                else
                {
                    cal(ans, prev, name, cur);
                    prev = null;
                    name.setLength(0);
                    cur = 0;
                    if (s[i] == '(')
                    {
                        prev = f(s, i + 1);
                        i = where + 1;
                    }
                    else
                    {
                        name.append(s[i++]);
                    }
                }
            }
            where = i;
            cal(ans, prev, name, cur);
            return ans;
        }

        void cal(TreeMap<String, Integer> ans, TreeMap<String, Integer> pre, StringBuilder name, int cnt)
        {
            boolean p1 = pre != null && !pre.isEmpty();
            boolean p2 = name.length() > 0;
            if (p1 || p2)
            {
                cnt = cnt == 0 ? 1 : cnt;
                if (p1)
                {
                    for (String key : pre.keySet())
                    {
                        ans.put(key, ans.getOrDefault(key, 0) + pre.get(key) * cnt);
                    }
                }
                if (p2)
                {
                    ans.put(name.toString(), ans.getOrDefault(name.toString(), 0) + cnt);
                }
            }
        }
    }
}
